package blog;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import db.Blog;
import db.SessionFactoryUtil;
import db.Users;

public class BlogHome {
	
	/**
	 * Pobranie artykulow
	 * @return List articles
	 */
	public static List getArticles() {
		Session session = SessionFactoryUtil.getSession();
		
		Query query = session.createQuery("from Blog");
		List list = query.list();
		if(list.isEmpty()) {
			return null;
		} else {
			return list;			
		}	
	}
	
	/**
	 * Usuniecie artykulu
	 */
	
	public static int removeArticle(int idB) {
		Session session = SessionFactoryUtil.getSession();
		
		Query query = session.createQuery("delete from Blog where idB = :idB");
		query.setParameter("idB", idB);
		int result = query.executeUpdate();
		return result;
	}
	
	/**
	 * Pobranie artykulu
	 */
	
	public static Blog getArticle(int idB) {
		Session session = SessionFactoryUtil.getSession();
		
		Query query = session.createQuery("from Blog where idB = :idB");
		query.setParameter("idB", idB);
		List list = query.list();
		if(list.isEmpty()) {
			return null;
		} else {
			return (Blog) list.get(0);			
		}	
	}
	
	/**
	 * Edycja artykulu
	 */
	
	public static int editArticle(Blog blog, int idB) {
		Session session = SessionFactoryUtil.getSession();

		Query query = session.createQuery("from Blog where idB = :idB");
		query.setParameter("idB", idB);
		List list = query.list();
		Blog bl = (Blog) list.get(0);
		
		bl.setTitle(blog.getTitle());
		bl.setContents(blog.getContents());
		bl.setData(blog.getData());

		session.update(bl);
		
		return 1;

	}
	



	
}



